import { createStore } from 'vuex'
import { getItem, setItem } from '../utils/storage'

const CARTLIST_KEY = 'localCartList'

export default createStore({
  state: {
    cartList: getItem(CARTLIST_KEY) || {}
  },
  mutations: {
    changeGoodsInfo (state, GoodsInfo) {
      const { shopId, goodsId, goodsInfo, num } = GoodsInfo
      // // 商店不存在，添加一个空商店
      const shop = state.cartList[shopId] || {}
      // 商品不存在，将 goodsInfo 信息赋给它
      let goods = shop[goodsId]
      if (!goods) {
        goods = {
          ...goodsInfo,
          count: 0,
          checked: false
        }
        // goods = goodsInfo
        // goods.count = 0
      }
      if (num > 0 && goods.count === 0) {
        goods.checked = true
      }
      // 按减号不能为0
      if (num < 0 && goods.count === 0) return
      // if (num < 0 && goods.count === 0) {
      //   // goods.count = 0
      //   return
      // }
      // 商品存在 加减
      goods.count += num
      // 数量为 1，点击 - 号，导致数量为 0 从 goodsInfo 中删除该商品
      if (num < 0 && goods.count === 0) return delete state.cartList[shopId][goodsId] // 从列表中删除
      // if (num < 0 && goods.count === 0) {
      //   delete state.cartList[shopId][goodsId] // 从列表中删除
      //   return
      // }
      shop[goodsId] = goods
      state.cartList[shopId] = shop // 因为是重新定义的 shop，goods 变量，不是直接对 cartList 进行操作，使用需要再将 goods、 shop 赋给 cartList
      setItem(CARTLIST_KEY, state.cartList)
    },
    // 购物车 每一个商品的选中按钮
    changeChecked (state, GoodsInfo) {
      const { shopId, goodsId, allBtn } = GoodsInfo
      const shop = state.cartList[shopId]
      const goods = shop[goodsId]
      goods.checked = !goods.checked
      let num = 0
      const arr = Object.keys(shop) // vuex 商店商品的信息
      for (const i in shop) {
        if (shop[i].checked) {
          num += 1 // 选中商品的数量
        }
      }
      // 选中的商品和 carList 中的商品数量一样，全选
      if (num === arr.length) { // 选中的商品和 carList 中的商品数量一样，全选
        allBtn.value = true
        return
      }
      allBtn.value = false
      setItem(CARTLIST_KEY, state.cartList)
    },
    // 购物车 全选按钮 控制每一个商品是否选中
    allChangeChecked (state, paylod) {
      const { shopId, allChecked } = paylod
      const shop = state.cartList[shopId]
      for (const i in shop) {
        shop[i].checked = allChecked
      }
      setItem(CARTLIST_KEY, state.cartList)
    },
    // 购物车 '清除所有商品' 按钮
    clearAllGoods (state, shopId) {
      state.cartList[shopId] = {}
      setItem(CARTLIST_KEY, state.cartList)
    }
  }
})
